<script setup lang="ts">
import { fetchRecordDetails, type LogDataRecord } from '@/api/admin/historyRecord'
import { rate } from '@/api/admin/public'

const router = useRouter()

const query = (useRoute().query || {
  medical_record_number: '',
  created_date: '',
}) as {
  medical_record_number: string
  created_date: string
}

const rateResult = ref()

const recordDetails = ref<LogDataRecord | null>(null)

// 语音识别记录接口
interface SpeechRecord {
  timestamp: string
  audio_path: string
  recognized_text: string | false
}

const speechRecords = ref<SpeechRecord[]>([])

const getRecordDetails = async () => {
  try {
    const response = await fetchRecordDetails(query.medical_record_number, query.created_date)
    if (response) {
      recordDetails.value = response
      if (recordDetails.value?.speech_analysis?.['recognition_log.jsonl']) {
        const url =
          `http://localhost:8000/${recordDetails.value.speech_analysis['recognition_log.jsonl']}`.replace(
            /\\+/g,
            '/',
          )
        fetchChatRecord(url)
      } else {
        ElMessage.warning('未找到聊天记录')
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.errorDetails.description || error?.message || '未知错误')
  }
}

// 解析JSONL数据的函数
const parseJsonL = (jsonlText: string) => {
  return jsonlText
    .trim()
    .split('\n')
    .filter((line) => line.trim() !== '') // 过滤空行
    .map((line) => {
      try {
        return JSON.parse(line)
      } catch (error) {
        console.error('解析JSON行失败:', line, error)
        return null
      }
    })
    .filter((item) => item !== null) // 过滤解析失败的行
}

// 解析语音识别数据
const fetchChatRecord = async (url: string) => {
  try {
    const response = await fetch(url)
    if (response.ok) {
      const data = await response.text()
      speechRecords.value = parseJsonL(data)
    }
  } catch (error: any) {
    ElMessage.error('获取聊天记录失败')
    console.error('获取聊天记录失败: ', error)
  }
}

// 获取音频URL
const getAudioUrl = (audioPath: string) => {
  if (audioPath.startsWith('http')) {
    return audioPath
  }
  return `http://localhost:8000/${audioPath}`
}

// 格式化timestamp
const formatTimestamp = (timestamp: string) => {
  if (timestamp.length === 8) {
    const year = timestamp.substring(0, 4)
    const month = timestamp.substring(4, 6)
    const day = timestamp.substring(6, 8)
    return `${year}-${month}-${day}`
  }
  return timestamp
}

const question = ref<Record<string, string>>({})

const fechQuestion = async () => {
  try {
    const response = await fetch('http://localhost:8000/static/speech.json')
    if (response.ok) {
      question.value = await response.json()
    }
  } catch (error: any) {
    ElMessage.error('获取评分失败')
    console.error('获取评分失败: ', error)
  }
}

const handleSubmit = async () => {
  if (!rateResult.value && rateResult.value !== 0) {
    ElMessage.warning('请先选择评分')
    return false
  }
  try {
    await rate({
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
      category: 'speech_analysis',
      score: rateResult.value,
    })
    router.push({
      path: '/semantic',
      query: {
        medical_record_number: query.medical_record_number,
        created_date: query.created_date,
      },
    })
  } catch (error) {
    ElMessage.error('评分失败')
    console.error('评分失败: ', error)
  }
}

const handleBack = () => {
  router.push({
    path: '/handwriting',
    query: {
      medical_record_number: query.medical_record_number,
      created_date: query.created_date,
    },
  })
}

onMounted(() => {
  fechQuestion()
  getRecordDetails()
})
</script>

<template>
  <el-row :gutter="48" class="h-full -mr-6">
    <el-col :span="12" class="h-full">
      <div class="h-full w-full px-2 py-4 border border-#D1D1D1 rounded shadow-lg overflow-auto">
        <div class="text-brand text-xl mb-4">语音识别结果</div>
        <div v-if="speechRecords.length === 0" class="text-brand text-lg">暂无语音识别数据</div>
        <div v-else class="space-y-4">
          <div
            v-for="(record, index) in speechRecords"
            :key="index"
            class="border border-#E5E5E5 rounded p-3"
          >
            <!-- 识别文本 -->
            <div class="text-brand text-base mb-2">
              <div class="font-medium mb-1">{{ formatTimestamp(record.timestamp) }}:</div>
              <div v-if="record.recognized_text === false" class="text-red-500">识别失败</div>
              <div v-else class="whitespace-pre-wrap">
                {{ record.recognized_text }}
              </div>
            </div>
            <!-- 音频播放器 -->
            <audio controls class="w-full" :src="getAudioUrl(record.audio_path)">
              您的浏览器不支持音频播放。
            </audio>
          </div>
        </div>
      </div>
    </el-col>
    <el-col :span="12" class="h-full overflow-auto pr-6">
      <div class="text-brand text-2xl">当前结果：</div>
      <div class="text-#00BA3D font-500 mt-4">
        <span class="text-4xl">{{ rateResult || 0 }}</span>
        <span class="text-lg ml-1">分</span>
      </div>
      <div class="text-brand text-lg mt-4">{{ question[rateResult] || '' }}</div>
      <div class="text-#0167bc text-2xl mt-12">结果修改：</div>
      <el-radio-group v-model="rateResult" class="mt-4">
        <el-radio v-for="rate in Object.keys(question)" :key="rate" :value="Number(rate)">
          {{ question[rate] }}
        </el-radio>
      </el-radio-group>
      <div class="flex items-center justify-evenly gap-8 mt-12">
        <el-button type="primary" class="flex-1" @click="handleSubmit">提交结果</el-button>
        <el-button class="brand-dark-button flex-1" @click="handleBack">返回上一页</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<style lang="css" scoped>
:deep(.el-radio) {
  display: block;
  width: 100%;
}
:deep(.el-radio) {
  --el-color-primary: #508bcc;
  --el-radio-font-size: 16px;
  margin-bottom: 8px;
}
:deep(.el-button) {
  padding: 18px 0;
}
</style>
